﻿using System;

namespace WeixinSDK.API
{
    /// <summary>
    /// 微信API访问凭据
    /// </summary>
    public static class AccessToken
    {
        /// <summary>
        /// 获取微信接口访问凭证
        /// </summary>
        /// <param name="tokenFolder">访问凭证缓存文件夹</param>
        /// <param name="appid">第三方用户唯一凭证</param>
        /// <param name="secret">第三方用户唯一凭证密钥，即appsecret</param>
        /// <returns></returns>
        public static string Get(WxSetting setting)
        {
            AccessTokenModel token = null;

            //---首先从缓存文件中提取

            var tokenFile = System.IO.Path.Combine(setting.TokenCacheFolder, "weixin.appid." + setting.AppId);

            if (System.IO.File.Exists(tokenFile))
            {
                Program.logger.Debug(" [Get Access Token From Cache] ");

                var json = System.IO.File.ReadAllText(tokenFile);
                token = WxJson.DeserializeObject<AccessTokenModel>(json);
            }

            //检查凭据是否过期，如果过期重新获取并获村

            if (token == null || token.ExpiredTime < DateTime.Now)
            {
                var url = WxApiHelper.BuildAccessTokenUrl(setting.AppId, setting.AppSecret);

                var json = WxWebClient.HttpGet(url);

                Program.logger.Debug(" [Get Access Token] " + json);

                token = WxJson.DeserializeObject<AccessTokenModel>(json);

                if (token.HasError)
                {
                    var errMsg = string.Format("Failure to get access token,error code:{0},error message:{1}", token.errcode, token.errmsg);
                    Program.logger.Error(errMsg);
                    throw new WxException(errMsg);
                }

                token.ExpiredTime = DateTime.Now.AddSeconds(token.expires_in - 100);

                //缓存在文件中
                json = WxJson.SerializeObject(token);
                System.IO.File.WriteAllText(tokenFile, json);
            }

            return token.access_token;
        }

        class AccessTokenModel : WxError
        {
            /// <summary>
            /// 获取到的凭证
            /// </summary>
            public string access_token { get; set; }
            /// <summary>
            /// 凭证有效时间，单位：秒
            /// </summary>
            public long expires_in { get; set; }

            /// <summary>
            /// 自定义字段,用于凭证缓存
            /// </summary>
            public DateTime ExpiredTime { get; set; }
        }
    }
}
